export const baseUrl = "http://localhost:8090";

// 使用 type 替代 interface 避免编译错误
type RequestOptions = {
	url : string;
	method ?: 'OPTIONS' | 'GET' | 'HEAD' | 'POST' | 'PUT' | 'DELETE' | 'TRACE' | 'CONNECT';
	header ?: any;
	data ?: any;
};

// 文件上传选项类型
type UploadOptions = {
	url : string;
	filePath : string;
	name : string;
	header ?: any;
};

// 定义 uni.uploadFile 的响应类型
type UploadFileResponse = {
	errMsg : string;
	statusCode : number;
	data : string;
	header ?: any; // 添加header属性，某些平台支持
};
// 请求拦截
const request = (options : RequestOptions) => {
	return new Promise((resolve, reject) => {
		const token = uni.getStorageSync('token');
		const retoken = uni.getStorageSync('retoken');
		const header = {
			'Content-Type': 'application/json',
			...options.header
		};
		if (token) {
			header['authorization'] = 'Bearer ' + token;
			header['retoken'] = 'Bearer ' + retoken;
		}
		uni.request({
			url: baseUrl + options.url,
			method: options.method || "GET",
			header,
			data: options.data,
			success: (res) => {
				// 检查响应头中的 authorization（token刷新后返回的新token）
				const newToken = res.header ? res.header['authorization'] || res.header['Authorization'] : null;
				if (newToken) {
					// 如果返回的是Bearer格式，去掉前缀
					const token = newToken.startsWith('Bearer ') ? newToken.substring(7) : newToken;
					// 更新本地存储的 token
					(uni as any).setStorageSync('token', token);
				}

				if (res.statusCode === 401 || (res.data as any).code === 401) {
					uni.removeStorageSync('token');
					uni.showToast({
						title: '登录已过期，请重新登录',
						icon: 'none'
					});
					setTimeout(() => {
						uni.navigateTo({
							url: '/pages/mine/mine'
						});
					}, 1500);
					reject(res);
					return;
				}
				resolve(res);
			},
			fail: (err) => {
				uni.showToast({
					title: '网络请求失败',
					icon: 'none'
				});
				reject(err);
			}
		});
	});
};
// 响应拦截

// 文件上传函数
const upload = (options : UploadOptions) => {
	return new Promise((resolve, reject) => {
		const token = uni.getStorageSync('token');
		const retoken = uni.getStorageSync('retoken');
		const header = {
			...options.header
		};
		if (token) {
			header['authorization'] = 'Bearer ' + token;
			header['retoken'] = 'Bearer ' + retoken;
		}

		// 使用 uni.uploadFile 进行文件上传
		(uni as any).uploadFile({
			url: baseUrl + options.url,
			filePath: options.filePath,
			name: options.name,
			header,
			success: (res : UploadFileResponse) => {
				// 检查响应头中的 authorization（token刷新后返回的新token）
				if (res.header) {
					const newToken = res.header['authorization'] || res.header['Authorization'];
					if (newToken) {
						// 如果返回的是Bearer格式，去掉前缀
						const token = newToken.startsWith('Bearer ') ? newToken.substring(7) : newToken;
						// 更新本地存储的 token
						(uni as any).setStorageSync('token', token);
					}
				}

				// 解析响应数据
				try {
					const data = JSON.parse(res.data);
					resolve({
						...res,
						data: data
					});
				} catch (e) {
					// 如果解析失败，直接返回原始响应
					resolve(res);
				}
			},
			fail: (err : any) => {
				uni.showToast({
					title: '文件上传失败',
					icon: 'none'
				});
				reject(err);
			}
		});
	});
};

export const get = (url : string, data ?: any, header ?: any) => {
	return request({ url, data, header, method: 'GET' });
};

export const post = (url : string, data ?: any, header ?: any) => {
	return request({ url, data, header, method: 'POST' });
};

export const put = (url : string, data ?: any, header ?: any) => {
	return request({ url, data, header, method: 'PUT' });
};

export const del = (url : string, data ?: any, header ?: any) => {
	return request({ url, data, header, method: 'DELETE' });
};

// 导出上传函数
export const uploadFile = (url : string, filePath : string, name : string, header ?: any) => {
	return upload({ url, filePath, name, header });
};